package cn.wolfcode.web.controller;

import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.utils.RequestPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.*;

@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService ;
    @Autowired
    private ApplicationContext cxt ;


    @RequestMapping("/list")
    public String list(Model model , QueryObject qo){
        PageInfo<Permission> pageInfo = permissionService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "permission/list" ;
    }

    @RequestMapping("/load")
    @ResponseBody
    public JsonResult load() {
        Set<Permission> permissions = new LinkedHashSet<>();

        List<Permission> allPermissions = permissionService.selectAll();

        //获取控制器存入map中
        Map<String, Object> map = cxt.getBeansWithAnnotation(Controller.class);
        //通过map.values 获取控制器对象
        Collection<Object> controllers = map.values();
        try {
            for (Object controller : controllers) {
                Method[] methods = controller.getClass().getDeclaredMethods();
                for (Method method : methods) {
                    RequestPermission annotation = method.getAnnotation(RequestPermission.class);
                    if (annotation != null) {
                        Permission permission = new Permission();
                        permission.setName(annotation.name());
                        permission.setExpression(annotation.expression());

                        if (!allPermissions.contains(permission)) {
                            System.out.println("permission = " + permission);
                            System.out.println("allPermissions = " + allPermissions);
                            permissions.add(permission);
                        }
                    }
                }
            }
            if (permissions.size() > 0) {
                permissionService.batchInsert(permissions);
            }
            return new JsonResult(true, "加载成功");
        }catch (Exception e){
            return new JsonResult(false, "加载失败");
        }
    }


}
